﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using JumbotPay.API.WxPayAPI;
namespace JumbotPay.WebFile.WxPay
{
    public partial class _notify_url : JumbotPay.UI.BasicPage
    {
        public string account_wxpay = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Charset = "utf-8";
            Response.ContentType = "text/xml";
            account_wxpay = q("account_no");

            if (SaveDebugLogs)
                JumbotPay.Utils.Logs.SaveLogs("debug_wxpay_notify_url",Request.Url.ToString());
                    

            WxPayConfig conf = new WxPayConfig(account_wxpay);
            WxPayData notifyData = GetNotifyData(conf.KEY);

            if (notifyData.IsSet("bank_type"))//支付通知
            {
                string _out_trade_no = notifyData.GetValue("out_trade_no").ToString();
                WxPayData res = new WxPayData();
                if (notifyData.GetValue("return_code").ToString() == "SUCCESS")
                {
                    
                    new JumbotPay.DAL.OrderDAL().UpdateOrder("wxpay", _out_trade_no, _out_trade_no);
                }
                res.SetValue("return_code", "SUCCESS");
                res.SetValue("return_msg", "OK");
                Response.Write(res.ToXml());
                Response.End();
            }
            else
            {
                //检查openid和product_id是否返回
                if (!notifyData.IsSet("openid") || !notifyData.IsSet("product_id"))
                {
                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", "回调数据异常");
                    Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
                    Response.Write(res.ToXml());
                    Response.End();
                }

                //调统一下单接口，获得下单结果
                string openid = notifyData.GetValue("openid").ToString();
                string order_id = notifyData.GetValue("product_id").ToString();
                WxPayData unifiedOrderResult = new WxPayData();
                try
                {
                    unifiedOrderResult = UnifiedOrder(openid, order_id);
                }
                catch (Exception ex)//若在调统一下单接口时抛异常，立即返回结果给微信支付后台
                {
                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", "统一下单失败[异常]");
                    Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml() + "\r\nopenid：" + openid + "\r\nproduct_id：" + order_id + "\r\n" + ex.Message);

                    Response.Write(res.ToXml());
                    Response.End();
                }

                //若下单失败，则立即返回结果给微信支付后台
                if (!unifiedOrderResult.IsSet("appid") || !unifiedOrderResult.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id"))
                {
                    WxPayData res = new WxPayData();
                    res.SetValue("return_code", "FAIL");
                    res.SetValue("return_msg", "统一下单失败[缺少参数]");
                    Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
                    Response.Write(res.ToXml());
                    Response.End();
                }



                //统一下单成功,则返回成功结果给微信支付后台
                WxPayData data = new WxPayData();
                data.SetValue("return_code", "SUCCESS");
                data.SetValue("return_msg", "OK");
                data.SetValue("appid", conf.APPID);//公众帐号id
                data.SetValue("mch_id", conf.MCHID);//商户号
                data.SetValue("nonce_str", new WxPayApi().GenerateNonceStr());
                data.SetValue("prepay_id", unifiedOrderResult.GetValue("prepay_id"));
                data.SetValue("result_code", "SUCCESS");
                data.SetValue("err_code_des", "OK");
                data.SetValue("sign", data.MakeSign(conf.KEY));

                Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml());
                Response.Write(data.ToXml());
                Response.End();
            }
        }
        /// <summary>
        /// 这里要结合实际的业务了
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="_order_id"></param>
        /// <returns></returns>
        private WxPayData UnifiedOrder(string openId, string _order_id)
        {
            //统一下单
            //Log.Info(this.GetType().ToString(), "统一下单 b");
            WxPayData req = new WxPayData();
            object[] _value = new JumbotPay.DAL.OrderDAL().GetOrderFields("wxpay", _order_id, "", "product_name,product_desc,pay_amount");
            string subject = _value[0].ToString();                            //商品名称
            string body = _value[1].ToString();                                 //商品描述
            string pay_amount = _value[2].ToString();


            string _out_trade_no = new WxPayApi().GenerateOutTradeNo(account_wxpay);
            //下单前先更新out_trade_no到ixueshu_normal_user_recharge
            _out_trade_no=new JumbotPay.DAL.OrderDAL().UpdateOutOrderNO(_order_id, _out_trade_no);

           

            req.SetValue("body", body);
            req.SetValue("attach", _order_id);
            req.SetValue("out_trade_no",_out_trade_no);
            req.SetValue("total_fee", Str2Double(_value[2].ToString())*100);
            req.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            req.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            req.SetValue("goods_tag", subject);
            req.SetValue("trade_type", "NATIVE");
            req.SetValue("openid", openId);
            req.SetValue("product_id", _order_id);


            WxPayData result = new WxPayApi().UnifiedOrder(req, account_wxpay,6);
            //Log.Info(this.GetType().ToString(), "统一下单 e");
            return result;
        }
        /// <summary>
        /// 接收从微信支付后台发送过来的数据并验证签名
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        public WxPayData GetNotifyData(string key)
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

            //Log.Info(this.GetType().ToString(), "从微信返回的数据 : " + builder.ToString());

            //转换数据格式并验证签名
            WxPayData data = new WxPayData();

            try
            {
                data.FromXml(builder.ToString(),key);
            }
            catch (WxPayException ex)
            {
                //若签名错误，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                Log.Error(this.GetType().ToString(), "签名验证失败 : " + res.ToXml());
                Response.Write(res.ToXml());
                Response.End();
            }

            //Log.Info(this.GetType().ToString(), "签名验证成功");
            return data;
        }
    }
}